//
//  OISerialConsoleWindowController.m
//  OrchIDE
//
//  Created by local22 on 8/14/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "OISerialConsoleWindowController.h"


@implementation OISerialConsoleWindowController
- (id)initWithWindow:(NSWindow *)window
{
	self = [super initWithWindow:window];
	if(!self) {
		return nil;
	}
	
	[self setEchoEnabled:NO];
	
	return self;
}

- (NSString *)windowNibName
{
	return @"OISerialConsole";
}

- (void)dealloc
{
	[self setEmulator:nil];
	
	[super dealloc];
}

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
	if([menuItem action] == @selector(toggleEchoEnabled:)) {
		[menuItem setTitle:_isEchoEnabled ? @"Disable Echo" : @"Enable Echo"];
	}
	
	return YES;
}

- (void)setEmulator:(OIEmulator *)emulator
{
	if(emulator == _emulator) {
		return;
	}
	
	[_emulator setSerialPortDelegate:nil];
	[_emulator release];
	_emulator = [emulator retain];
	[_emulator setSerialPortDelegate:self];
}

- (BOOL)isEchoEnabled
{
	return _isEchoEnabled;
}

- (void)setEchoEnabled:(BOOL)flag
{
	_isEchoEnabled = flag;
}

- (IBAction)toggleEchoEnabled:(id)sender
{
	[self setEchoEnabled:![self isEchoEnabled]];
}

- (NSString *)windowTitleForDocumentDisplayName:(NSString *)displayName
{
	return [NSString stringWithFormat:@"%@ - Serial Console", displayName];
}

- (void)emulator:(OIEmulator *)emulator didReadByteFromSerialPort:(uint8_t)byte
{
	if(byte == 0x08 || byte == 0x7F) {
		if([[_consoleView textStorage] length] > 1) {
			[[_consoleView textStorage] deleteCharactersInRange:NSMakeRange([[_consoleView textStorage] length] - 2, 2)];
		}
		return;
	}

	NSString *stringToAppend = [NSString stringWithFormat:@"%C%c", 0x200B /* zwsp */, byte];
	NSDictionary *attributes = [NSDictionary dictionaryWithObject:[NSFont fontWithName:@"Monaco" size:10] forKey:NSFontAttributeName];
	[[_consoleView textStorage] appendAttributedString:[[[NSAttributedString alloc] initWithString:stringToAppend attributes:attributes] autorelease]];
	[_consoleView scrollRangeToVisible:NSMakeRange([[_consoleView textStorage] length] - 1, 0)];
}

- (void)keyDown:(NSEvent *)e
{
	NSString *characters = [e characters];
	if([characters length] == 0) {
		return;
	}
	
	uint8_t byte = (uint8_t)[characters characterAtIndex:[characters length] - 1];
	[_emulator writeByteToSerialPort:byte];
	
	if(_isEchoEnabled) {
		[self emulator:_emulator didReadByteFromSerialPort:byte];
	}
}

@end
